<script setup>
  import PageContainer from '@/components/PageContainer.vue'
  import { useUserStore } from '@/stores'
  import { ref, nextTick } from 'vue'
  import { Plus } from '@element-plus/icons-vue'
  import { userUpdateAvatarServce } from '@/api/user'
  const userStore = useUserStore()
  // 回显头像图片
  const imageUrl = ref(userStore.user.user_pic)

  //更改用户头像
  const uploadRef = ref()

  const selectorImg = file => {
    // 基于 FileReader 读取图片做预览
    const reader = new FileReader()
    reader.readAsDataURL(file.raw)
    reader.onload = () => {
      imageUrl.value = reader.result
    }
  }
  const updateAvater = async () => {
    // 更换头像
    await userUpdateAvatarServce(imageUrl.value)
    // 获取头像
    await userStore.getuser()
    ElMessage.success('头像更改成功')
  }
</script>
<template>
  <page-container title="更换头像">
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :auto-upload="false"
      ref="uploadRef"
      :on-change="selectorImg"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <br />
    <!-- 单击时触发img点击效果，通过el.querySelector获取其中dom元素input点击事件 -->
    <el-button
      @click="uploadRef.$el.querySelector('input').click()"
      type="primary"
    >
      选择图片
    </el-button>
    <el-button @click="updateAvater" type="success">更换头像</el-button>
  </page-container>
</template>

<style lang="scss" scoped>
  .avatar-uploader {
    :deep() {
      .avatar {
        width: 250px;
        height: 250px;
        display: block;
      }
      .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
      }
      .el-upload:hover {
        border-color: var(--el-color-primary);
      }
      .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 250px;
        height: 250px;
        text-align: center;
      }
    }
  }
</style>
